<template>
  <view
    class="tn-row-notice"
    :class="[noticeClass]"
    :style="noticeStyle"
  >
    <!-- 左图标 -->
    <view
      v-if="!!leftIcon"
      class="tn-row-notice__left-icon"
      :class="[leftIconClass]"
      :style="leftIconStyle"
      @tap.stop="handleLeftIconClick"
    >
      <tn-icon :icon="leftIcon"></tn-icon>
    </view>
    <!-- 通知内容 -->
    <view class="tn-row-notice__content" @tap.stop="handleNoticeClick">
      <view
        :id="id"
        class="tn-row-notice__content--data"
        :style="contentStyle"
        :animation="animationData"
      >
        <view :id="`${id}-text`" class="tn-row-notice__content--text">
          {{ content }}
        </view>
      </view>
    </view>
    <!-- 右图标 -->
    <view
      v-if="!!rightIcon"
      class="tn-row-notice__right-icon"
      :class="[rightIconClass]"
      :style="rightIconStyle"
      @tap.stop="handleRightIconClick"
    >
      <tn-icon :icon="rightIcon"></tn-icon>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { rowNoticeProps, rowNoticeEmits } from '../../../types/tn-notice-bar'
import { 
  computed, 
  watchEffect, 
  CSSProperties, 
  ref, 
  watch, 
  getCurrentInstance, 
  ComponentInternalInstance, 
  nextTick, 
  onMounted 
} from 'vue'
import { ColorInfo } from '../../../types/tuniao-ui'
import useComponentColor from '../../../libs/hooks/useComponentColor'
import { handleValueWithUnit, uuid, getRectInfo } from '../../../utils'
import TnIcon from '../../tn-icon/src/Icon.vue'

const props = defineProps(rowNoticeProps)
const emits = defineEmits(rowNoticeEmits)

const { generateColorInfo, splitColorInfo } = useComponentColor()
let componentColorInfo = generateColorInfo(props?.color || '', props?.bgColor || '')
// 监听颜色变化实时修改颜色对应的属性
watchEffect(() => {
  componentColorInfo = generateColorInfo(props?.color || '', props?.bgColor || '')
})

// 解析左图标颜色
const leftIconColor = computed<ColorInfo>(() => {
  return splitColorInfo('color', props?.leftIconColor || '')
})
// 解析右图标颜色
const rightIconColor = computed<ColorInfo>(() => {
  return splitColorInfo('color', props?.rightIconColor || '')
})

// 通知栏样式
const noticeStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (componentColorInfo.style?.color) {
    style.color = componentColorInfo.style.color
  }
  if (componentColorInfo.style?.backgroundColor) {
    style.backgroundColor = componentColorInfo.style.backgroundColor
  }
  if (props?.fontSize) {
    style.fontSize = handleValueWithUnit(props.fontSize)
  }

  return Object.assign(style, props?.customStyle || {})
})
// 通知内容样式
const contentStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  
  return style
})
// 左图标样式
const leftIconStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (leftIconColor.value.type === 'style') {
    style.color = leftIconColor.value.value
  }
  if (!!props?.leftIconSize) {
    style.fontSize = handleValueWithUnit(props.leftIconSize)
  }
  return style
})
// 右图标样式
const rightIconStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (rightIconColor.value.type === 'style') {
    style.color = rightIconColor.value.value
  }
  if (!!props?.rightIconSize) {
    style.fontSize = handleValueWithUnit(props.rightIconSize)
  }
  return style
})

// 通知栏对应的类
const noticeClass = computed<string>(() => {
  let clazz: string[] = []

  if (componentColorInfo.class.length > 0) {
    clazz.push(...componentColorInfo.class)
  }
  if (props?.fontBold) {
    clazz.push('tn-text-bold')
  }
  // 设置默认type
  if (props?.type) {
    clazz.push(`tn-type-${props.type}`)
  }

  return clazz.join(' ')
})
// 左图标对应的类
const leftIconClass = computed<string>(() => {
  let clazz: string[] = []
  if (leftIconColor.value.type === 'class') {
    clazz.push(leftIconColor.value.value)
  }
  return clazz.join(' ')
})
// 右图标对应的类
const rightIconClass = computed<string>(() => {
  let clazz: string[] = []
  if (rightIconColor.value.type === 'class') {
    clazz.push(rightIconColor.value.value)
  }
  return clazz.join(' ')
})

// 显示的内容，将数字转换为字符串
const content = computed<string>(() => {
  if (props?.data?.length > 0) {
    return props.data.join(' ')
  }
  return ''
})

// 通知运动参数
let animationDuration: number = 0
let animation: UniApp.Animation | null = null
let animationData = ref<any>(null)
// 通知动画状态
watch(() => props.playStatus, (val: string) => {
  if (val === 'play') {
    createLoopAnimation()
  } else {
    stopAnimation()
  }
})

// 初始化通知栏
const id = uuid()
const instance = getCurrentInstance() as ComponentInternalInstance
let initCount: number = 0
let contentWidth: number = 0
let contentTextWidth: number = 0
let animationLoopTimer: number | null = null
const initNotice = async () => {
  const contentRect = await getRectInfo(`#${id}`, instance)
  const contentTextRect = await getRectInfo(`#${id}-text`, instance)
  if (!contentRect || !contentRect.width || !contentTextRect || !contentTextRect.width) {
    if (initCount > 10) {
      console.error('[tn-notice-bar]初始化通知栏失败, 获取组件数据失败')
      return
    }
    setTimeout(() => {
      initNotice()
      initCount++
    }, 50);
    return
  }

  initCount = 0
  // 根据t=s/v(时间=路程/速度)
  const speed = props?.speed ? Number(props.speed) : 160
  contentWidth = contentRect.width || 0
  contentTextWidth = contentTextRect.width || 0
  animationDuration = (contentWidth + contentTextWidth) / uni.upx2px(speed) * 1000
  console.log(contentWidth, contentTextWidth, animationDuration);
  setTimeout(() => {
    if (props?.autoplay && props?.playStatus === 'play') createLoopAnimation()
  }, 50);
}

// 创建动画
const createAnimation = () => {
  animation = uni.createAnimation({
    duration: animationDuration,
    timingFunction: 'linear'
  })
  animation.translateX(-(contentWidth + contentTextWidth) + Number(Math.random() * 10)).step({
    duration: animationDuration
  })
  animation.translateX(0).step({
    duration: 0
  })
  animationData.value = animation.export()
}
// 创建循环动画
const createLoopAnimation = () => {
  createAnimation()
  animationLoopTimer = setInterval(() => {
    createAnimation()
  }, animationDuration + 20)
}
// 停止动画
const stopAnimation = () => {
  animation = null
  animationData.value = null
  if (animationLoopTimer) {
    clearInterval(animationLoopTimer)
    animationLoopTimer = null
  }
}

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      initNotice()
    }, 50);
  })
  
})

// 修改了速度重新初始化
watch(() => props.speed, () => {
  initNotice()
})

// 点击左图标事件
const handleLeftIconClick = () => {
  emits('left-click')
}
// 点击右图标事件
const handleRightIconClick = () => {
  emits('right-click')
}
// 点击通知事件
const handleNoticeClick = () => {
  emits('click', 0)
}
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>

.tn-row-notice {
  width: 100%;
  height: auto;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
  overflow: inherit;
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  line-height: 1.2em;
  vertical-align: middle;

  &__content {
    flex: 1;
    overflow: hidden;

    &--data {
      // display: inline-block;
      width: auto;
      min-width: 0;
      padding-left: 100%;
      // animation-name: tn-notice-loop-animation;
      // animation-timing-function: linear;
      // animation-iteration-count: infinite;
      // animation-fill-mode: both;
    }

    &--text {
      display: inline;
      word-break: keep-all;
      white-space: nowrap;
      width: auto;
      min-width: 0;
    }
  }

  &__left-icon {
    margin-right: 8rpx;
  }
  &__right-icon {
    margin-left: 8rpx;
  }
}

// @keyframes tn-notice-loop-animation {
//   0% {
//     transform: translateX(0);
//   }
//   100% {
//     transform: translateX(-100%);
//   }
// }
</style>
